package com.company.emallbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.emallbackend.entity.Collect;
import com.company.emallbackend.entity.Product;
import com.company.emallbackend.entity.User;
import com.company.emallbackend.exception.CommonException;
import com.company.emallbackend.mapper.CollectMapper;
import com.company.emallbackend.mapper.ProductMapper;
import com.company.emallbackend.service.ICollectService;
import com.company.emallbackend.utils.TokenUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hanlijian
 * @since 2023-01-13
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements ICollectService {
    @Resource
    private CollectMapper collectMapper;
    @Resource
    private ProductMapper productMapper;
    
    @Override
    public List<Collect> myCollectList() {
        User user = TokenUtils.getCurrentAdmin();
        Integer userId = user.getId();
        //根据userId查询收藏列表
        List<Collect> collectList = collectMapper.selectList(new QueryWrapper<Collect>().eq("user_id", userId));
        if(CollectionUtils.isEmpty(collectList)){
            return null;
        }
        List<Collect> collects=new ArrayList<>();
        for (Collect collect : collectList) {
            Integer productId = collect.getProductId();
            //根据商品id查询商品
            Product product = productMapper.selectById(productId);
            collect.setProduct(product);
            collects.add(collect);
        }
        return collects;
    }

    @Override
    public void addCollectProduct(Integer productId) {
        if(Objects.isNull(productId)){
            throw new CommonException(201,"请检查您要收藏的商品");
        }
        User user = TokenUtils.getCurrentAdmin();
        //每个商品只能点赞一次,防止重复点赞
        List<Collect> collects = collectMapper.selectList(new QueryWrapper<Collect>().eq("user_id", user.getId()));
        List<Integer> productIdList = collects.stream().map(Collect::getProductId).collect(Collectors.toList());
        if(productIdList.contains(productId)){
            throw new CommonException(201,"该商品已被您收藏");
        }
        collectMapper.insert(new Collect(user.getId(),productId));
        //添加商品表收藏量
        Product product = productMapper.selectById(productId);
        product.setCollection(product.getCollection()+1);
        productMapper.updateById(product);
    }
}
